package com.blvtphan.tipocketclubs.api;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

import com.blvtphan.tipocketclubs.api.ApiConstant.API;
import com.blvtphan.tipocketclubs.model.PlaceDataModel;
import com.blvtphan.tipocketclubs.model.PlaceDetailModel;
import com.blvtphan.tipocketclubs.model.RewardsModel;
import com.blvtphan.tipocketclubs.model.TrackerDetailModel;
import com.blvtphan.tipocketclubs.model.TrackerSummaryModel;
import com.blvtphan.tipocketclubs.system.UserSetting;

public class ApiHelper {

	/**
	 * Get API
	 * 
	 * @param api
	 * @return
	 */
	public static String genAPI(API api) {
		String result = "";
		String serverAdd = ApiConstant.SERVER;
//				.replace("{0}", UserSetting
//				.getInstance().getIpServer());

		switch (api) {

		case API_LOGIN:
			result = serverAdd + ApiConstant.REQUEST_USER_LOGIN;
			break;

		case API_UPDATE_DEVICE_ID:
			result = serverAdd + ApiConstant.REQUEST_UPDATE_DEVICE_ID;
			break;

		case API_SEND_MSG:
			result = serverAdd + ApiConstant.REQUEST_SEND_MSG;
			break;

		case API_GET_MERCHANTS:
			result = serverAdd + ApiConstant.REQUEST_GET_MERCHANTS;
			break;
			
		case API_GET_TRACKER_SUMMARY:
			result = serverAdd + ApiConstant.REQUEST_GET_TRACKER_SUMMARY;
			break;
			
		case API_GET_TRACKER_DETAIL:
			result = serverAdd + ApiConstant.REQUEST_GET_TRACKER_DETAIL;
			break;
			
		case API_GET_MERCHANTS_LIMIT:
			result = serverAdd + ApiConstant.REQUEST_GET_MERCHANTS_LIMIT;
			break;
			
		case API_POST_CHECK_MERCHANT_CODE:
			result = serverAdd + ApiConstant.REQUEST_POST_CHECK_MERCHANT_CODE;
			break;
			
		case API_POST_SUBMIT_TRACKER:
			result = serverAdd + ApiConstant.REQUEST_POST_SUBMIT_TRACKER;
			break;
			
		default:
			result = "";
			break;
		}

		return result;
	}

	/**
	 * 
	 * @param email
	 * @param password
	 * @return
	 * @throws JSONException
	 */
	public static JSONObject getJSONObjectLogin(String email, String password)
			throws JSONException {
		JSONObject obj = new JSONObject();
		obj.put(ApiConstant.User.EMAIL, email);
//		obj.put(ApiConstant.User.PASSWORD, GeneralUtils.encryptMD5(password));
		obj.put(ApiConstant.User.PASSWORD, password);

		return obj;
	}

	/**
	 * 
	 * @param deviceId
	 * @return
	 * @throws JSONException
	 */
	public static JSONObject getJSONObjectUpdateDeviceId(String deviceId)
			throws JSONException {
		JSONObject obj = new JSONObject();
		obj.put(ApiConstant.User.ID,
				String.valueOf(UserSetting.getInstance().getUserId()));
		obj.put(ApiConstant.User.DEVICE_ID, deviceId);

		return obj;
	}

	/**
	 * 
	 * @param userId
	 * @param msg
	 * @param date
	 * @return
	 * @throws JSONException
	 */
	public static JSONObject getJSONObjectSendMsg(long userId, String msg,
			long date) throws JSONException {
		JSONObject obj = new JSONObject();
		obj.put(ApiConstant.Message.USER_ID, String.valueOf(userId));
		obj.put(ApiConstant.Message.MESSAGE, msg);
		obj.put(ApiConstant.Message.DATE, String.valueOf(date));

		return obj;
	}

	/**
	 * 
	 * @param msg
	 */
	public static void parseMsgAndDisplay(Context context, String msg) {
		try {
			JSONObject objMsg = new JSONObject(msg);
			String message = objMsg.getString(ApiConstant.Message.MESSAGE);
			Date date = new Date(Long.valueOf(objMsg
					.getString(ApiConstant.Message.DATE)));
			String fullName = objMsg.getString(ApiConstant.User.USER_FULL_NAME);
			//MainActivity.addMsg(context, message, date, fullName, false);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * @param context
	 * @param data
	 */
	public static List<PlaceDetailModel> parseJSONGetAllMerchants(Context context, String data) {
		List<PlaceDetailModel> lstMerchants = new ArrayList<PlaceDetailModel>();
		
		try {
			JSONObject bigObj = new JSONObject(data);
			Log.i("JSON", "json merchants: "+bigObj.toString());
			JSONObject dataObj = bigObj.getJSONObject(ApiConstant.JsonType.DATA);
			int total = 0;
			if(!dataObj.isNull(ApiConstant.MerchantDetails.TOTAL)) {
				total = dataObj.getInt(ApiConstant.MerchantDetails.TOTAL);
			}
			JSONArray arrMarchantsObj = dataObj.getJSONArray(ApiConstant.MerchantsDataConfig.ROWS);
			
			for(int i=0;i<arrMarchantsObj.length();i++) {
				
				PlaceDetailModel merchantModel = new PlaceDetailModel();
				JSONObject merchantObj = arrMarchantsObj.getJSONObject(i);
				
				String id="", name="", logoUrl="", address="", logo="", city="", country="", email="", website=""
						, userId="", code="", status="", category="";
				double lat=10, lng=100;
				
				if(!merchantObj.isNull(ApiConstant.MerchantDetails.ID))
					id = merchantObj.getString(ApiConstant.MerchantDetails.ID);
				if(!merchantObj.isNull(ApiConstant.MerchantDetails.NAME))
					name = merchantObj.getString(ApiConstant.MerchantDetails.NAME);
				if(!merchantObj.isNull(ApiConstant.MerchantDetails.MERCHANT_LOGO))
					logoUrl = merchantObj.getString(ApiConstant.MerchantDetails.MERCHANT_LOGO);
				if(!merchantObj.isNull(ApiConstant.MerchantDetails.ADDRESS))
					address = merchantObj.getString(ApiConstant.MerchantDetails.ADDRESS);
				if(!merchantObj.isNull(ApiConstant.MerchantDetails.LOGO))
					logo = merchantObj.getString(ApiConstant.MerchantDetails.LOGO);
				if(!merchantObj.isNull(ApiConstant.MerchantDetails.CITY))
					city = merchantObj.getString(ApiConstant.MerchantDetails.CITY);
				if(!merchantObj.isNull(ApiConstant.MerchantDetails.COUNTRY))
					country = merchantObj.getString(ApiConstant.MerchantDetails.COUNTRY);
				if(!merchantObj.isNull(ApiConstant.MerchantDetails.EMAIL))
					email = merchantObj.getString(ApiConstant.MerchantDetails.EMAIL);
				if(!merchantObj.isNull(ApiConstant.MerchantDetails.WEBSITE))
					website = merchantObj.getString(ApiConstant.MerchantDetails.WEBSITE);
				if(!merchantObj.isNull(ApiConstant.MerchantDetails.USER_ID))
					userId = merchantObj.getString(ApiConstant.MerchantDetails.USER_ID);
				if(!merchantObj.isNull(ApiConstant.MerchantDetails.CODE))
					code = merchantObj.getString(ApiConstant.MerchantDetails.CODE);
				if(!merchantObj.isNull(ApiConstant.MerchantDetails.LAT))
					lat = merchantObj.getDouble(ApiConstant.MerchantDetails.LAT);
				if(!merchantObj.isNull(ApiConstant.MerchantDetails.LNG))
					lng = merchantObj.getDouble(ApiConstant.MerchantDetails.LNG);
				if(!merchantObj.isNull(ApiConstant.MerchantDetails.STATUS))
					status = merchantObj.getString(ApiConstant.MerchantDetails.STATUS);
				if(!merchantObj.isNull(ApiConstant.MerchantDetails.CATEGORY_NAME))
					category = merchantObj.getString(ApiConstant.MerchantDetails.CATEGORY_NAME);
				
				List<RewardsModel> lstRewards = new ArrayList<RewardsModel>();
				
				JSONArray rewardsArr = merchantObj.getJSONArray(ApiConstant.MerchantDetails.REWARDS);
				
				for(int j=0;j<rewardsArr.length();j++) {
					RewardsModel rewardModel = new RewardsModel();
					JSONObject rewardObj = rewardsArr.getJSONObject(j);
					String rewardId = rewardObj.getString(ApiConstant.Rewards.ID);
					String title = rewardObj.getString(ApiConstant.Rewards.TITLE);
					String discount = rewardObj.getString(ApiConstant.Rewards.DISCOUNT_TEXT);
					String toDate = rewardObj.getString(ApiConstant.Rewards.TO_DATE);
					String toTime = rewardObj.getString(ApiConstant.Rewards.TO_TIME);
					String fromDate = rewardObj.getString(ApiConstant.Rewards.FROM_DATE);
					String fromTime = rewardObj.getString(ApiConstant.Rewards.FROM_TIME);
					rewardModel.setDiscount(discount);
					rewardModel.setId(rewardId);
					rewardModel.setTitle(title);
					rewardModel.setDiscount(discount);
					rewardModel.setFromDate(fromDate);
					rewardModel.setFromTime(fromTime);
					rewardModel.setToDate(toDate);
					rewardModel.setToTime(toTime);
					
					lstRewards.add(rewardModel);
				}
				
				merchantModel.setId(id);
				merchantModel.setAddress(address);
				merchantModel.setCategory(category);
				merchantModel.setLat(lat);
				merchantModel.setLng(lng);
				merchantModel.setMarchantLogo(logoUrl);
				merchantModel.setName(name);
				merchantModel.setLstRewards(lstRewards);
				merchantModel.setTotal(total);
				
				lstMerchants.add(merchantModel);
			}
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
		Log.i("JSON", "Merchant size: " + lstMerchants.size());
		return lstMerchants;
	}
	
	public static PlaceDataModel parseJSONGetPlaceData(Context context, String data) {
		PlaceDataModel placeDataModel = new PlaceDataModel();
		try {
			JSONObject bigObj = new JSONObject(data);
			Log.i("JSON", "json get merchants data: "+bigObj.toString());
			JSONObject dataObj = bigObj.getJSONObject(ApiConstant.JsonType.DATA);
			
			int start = dataObj.getInt(ApiConstant.MerchantsDataConfig.START);
			int limit = dataObj.getInt(ApiConstant.MerchantsDataConfig.LIMIT);
			int total = dataObj.getInt(ApiConstant.MerchantsDataConfig.TOTAL);
			
			placeDataModel.setLimit(limit);
			placeDataModel.setStart(start);
			placeDataModel.setTotal(total);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return placeDataModel;
	}
	
	public static TrackerSummaryModel parseJSONGetTrackerSummary(Context context, String data) {
		TrackerSummaryModel trackerSummary = new TrackerSummaryModel();
		try {
			JSONObject bigObj = new JSONObject(data);
			Log.i("JSON", "json get tracker summary: " + bigObj.toString());
			JSONObject dataObj = bigObj.getJSONObject(ApiConstant.JsonType.DATA);
			
			String spent="", saved="", used="";
			
			if(!dataObj.isNull(ApiConstant.TrackerSummary.TOTAL_SPENT))
				spent = dataObj.getString(ApiConstant.TrackerSummary.TOTAL_SPENT);
			if(!dataObj.isNull(ApiConstant.TrackerSummary.TOTAL_SAVED))
				saved = dataObj.getString(ApiConstant.TrackerSummary.TOTAL_SAVED);
			if(!dataObj.isNull(ApiConstant.TrackerSummary.TOTAL_USED))
				used = dataObj.getString(ApiConstant.TrackerSummary.TOTAL_USED);
			
			trackerSummary.setSpent(spent);
			trackerSummary.setSaved(saved);
			trackerSummary.setUsed(used);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return trackerSummary;
	}

	public static List<TrackerDetailModel> parseJSONGetTrackerDetail(Context mContext, String data) {
		// TODO Auto-generated method stub
		List<TrackerDetailModel> lstTrackerDetail = new ArrayList<TrackerDetailModel>();
		
		try {
			JSONObject bigObj = new JSONObject(data);
			Log.i("JSON", "json get tracker detail: " + bigObj.toString());
			JSONObject dataObj = bigObj.getJSONObject(ApiConstant.JsonType.DATA);

			JSONArray detailArr = dataObj.getJSONArray(ApiConstant.JsonType.DATA);
			for(int i=0;i<detailArr.length();i++) {
				TrackerDetailModel detailMode = new TrackerDetailModel();
				JSONObject detailObj = detailArr.getJSONObject(i);
				String id = detailObj.getString(ApiConstant.TrackerDetail.ID);
				String name = detailObj.getString(ApiConstant.TrackerDetail.NAME);
				String category = detailObj.getString(ApiConstant.TrackerDetail.CATEGORY);
				String logo = detailObj.getString(ApiConstant.TrackerDetail.LOGO);
				String visitDate = detailObj.getString(ApiConstant.TrackerDetail.VISIT_DATE);
				String spent = detailObj.getString(ApiConstant.TrackerDetail.SPENT);
				String saved = detailObj.getString(ApiConstant.TrackerDetail.SAVED);
				
				detailMode.setId(id);
				detailMode.setPlaceCategory(category);
				detailMode.setPlaceName(name);
				detailMode.setPlaceLogo(logo);
				detailMode.setVisitDate(visitDate);
				detailMode.setSpent(spent);
				detailMode.setSaved(saved);
				
				lstTrackerDetail.add(detailMode);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return lstTrackerDetail;
	}
}
